<template>
  <div class="procurement-plans">
    <!-- 页面标题 -->
    <PageHeader 
      title="采购计划" 
      description="制定和管理采购计划，包括需求预测、供应商选择等"
      icon="Calendar"
    />
    
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="计划名称">
          <el-input v-model="filterForm.name" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="待审批" value="pending" />
            <el-option label="已审批" value="approved" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleCreatePlan">创建计划</el-button>
      <el-button @click="handleImport">导入计划</el-button>
      <el-button @click="handleExport">导出计划</el-button>
    </div>
    
    <!-- 计划列表 -->
    <el-card class="list-card" shadow="never">
      <el-table :data="planList" style="width: 100%" v-loading="loading">
        <el-table-column prop="planNo" label="计划编号" width="150" />
        <el-table-column prop="name" label="计划名称" min-width="200" />
        <el-table-column prop="totalAmount" label="计划金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="计划状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="success" link @click="handleEdit(row)" v-if="['draft', 'pending'].includes(row.status)">编辑</el-button>
            <el-button type="warning" link @click="handleApprove(row)" v-if="row.status === 'pending'">审批</el-button>
            <el-button type="danger" link @click="handleDelete(row)" v-if="['draft', 'pending'].includes(row.status)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 计划对话框 -->
    <el-dialog v-model="planDialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="planForm" label-width="100px" ref="planFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" required>
              <el-input v-model="planForm.name" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行周期" required>
              <el-date-picker
                v-model="planForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input v-model="planForm.remark" type="textarea" />
        </el-form-item>
        
        <!-- 计划明细 -->
        <el-form-item label="计划明细">
          <el-table :data="planForm.items" style="width: 100%">
            <el-table-column prop="category" label="商品分类" width="120">
              <template #default="{ row }">
                <el-select v-model="row.category" placeholder="请选择分类">
                  <el-option label="电子产品" value="electronics" />
                  <el-option label="服装" value="clothing" />
                  <el-option label="配件" value="accessories" />
                  <el-option label="图书" value="books" />
                  <el-option label="软件" value="software" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.productName" placeholder="请输入商品名称" />
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格" width="120">
              <template #default="{ row }">
                <el-input v-model="row.specification" placeholder="请输入规格" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="计划数量" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" />
              </template>
            </el-table-column>
            <el-table-column prop="estimatedUnitPrice" label="预估单价" width="100">
              <template #default="{ row }">
                <el-input-number v-model="row.estimatedUnitPrice" :min="0" :precision="2" />
              </template>
            </el-table-column>
            <el-table-column prop="estimatedAmount" label="预估金额" width="120">
              <template #default="{ row }">
                ¥{{ (row.quantity * row.estimatedUnitPrice).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button type="danger" link @click="removePlanItem($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" @click="addPlanItem">添加商品</el-button>
          </div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预估总金额">
              <el-input v-model="totalEstimatedAmount" disabled>
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="planDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPlan">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from '@vue/runtime-core'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据模型
interface PlanItem {
  id: number
  category: string
  productName: string
  specification: string
  quantity: number
  estimatedUnitPrice: number
}

interface Plan {
  id: number
  planNo: string
  name: string
  totalAmount: number
  status: 'draft' | 'pending' | 'approved' | 'executing' | 'completed'
  creator: string
  createdAt: string
  startDate: string
  endDate: string
  remark: string
  items: PlanItem[]
}

// 筛选表单
const filterForm = reactive({
  name: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态
const loading = ref(false)
const planList = ref<Plan[]>([])
const planDialogVisible = ref(false)
const dialogTitle = ref('创建计划')
const isEdit = ref(false)

// 表单引用
const planFormRef = ref()

// 表单数据
const planForm = reactive({
  id: 0,
  name: '',
  dateRange: [] as string[],
  remark: '',
  items: [] as PlanItem[]
})

// 计算预估总金额
const totalEstimatedAmount = computed(() => {
  return planForm.items.reduce((sum, item) => sum + item.quantity * item.estimatedUnitPrice, 0)
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'draft': return 'info'
    case 'pending': return 'warning'
    case 'approved': return 'primary'
    case 'executing': return 'info'
    case 'completed': return 'success'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'draft': return '草稿'
    case 'pending': return '待审批'
    case 'approved': return '已审批'
    case 'executing': return '执行中'
    case 'completed': return '已完成'
    default: return '未知'
  }
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', filterForm)
  loadPlanList()
}

// 重置
const handleReset = () => {
  filterForm.name = ''
  filterForm.status = ''
  loadPlanList()
}

// 加载计划列表
const loadPlanList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    planList.value = [
      {
        id: 1,
        planNo: 'PP20251115001',
        name: '第四季度电子产品采购计划',
        totalAmount: 2500000,
        status: 'approved',
        creator: '张三',
        createdAt: '2025-11-15 09:30:00',
        startDate: '2025-11-20',
        endDate: '2025-12-31',
        remark: '满足年底销售需求',
        items: [
          { id: 1, category: 'electronics', productName: '智能手机', specification: '128G', quantity: 1000, estimatedUnitPrice: 2500 },
          { id: 2, category: 'electronics', productName: '平板电脑', specification: '256G', quantity: 500, estimatedUnitPrice: 3000 }
        ]
      },
      {
        id: 2,
        planNo: 'PP20251115002',
        name: '第一季度服装采购计划',
        totalAmount: 1200000,
        status: 'pending',
        creator: '李四',
        createdAt: '2025-11-15 14:20:30',
        startDate: '2026-01-01',
        endDate: '2026-03-31',
        remark: '春季新品采购',
        items: [
          { id: 1, category: 'clothing', productName: '男士衬衫', specification: '42码', quantity: 2000, estimatedUnitPrice: 200 },
          { id: 2, category: 'clothing', productName: '女士连衣裙', specification: 'M码', quantity: 1500, estimatedUnitPrice: 300 }
        ]
      }
    ]
    pagination.total = 20
    loading.value = false
  }, 500)
}

// 操作按钮
const handleCreatePlan = () => {
  dialogTitle.value = '创建计划'
  isEdit.value = false
  resetPlanForm()
  planDialogVisible.value = true
}

const handleImport = () => {
  console.log('导入计划')
}

const handleExport = () => {
  console.log('导出计划')
}

// 查看计划
const handleView = (row: Plan) => {
  console.log('查看计划:', row)
}

// 编辑计划
const handleEdit = (row: Plan) => {
  dialogTitle.value = '编辑计划'
  isEdit.value = true
  Object.assign(planForm, row)
  planForm.dateRange = [row.startDate, row.endDate]
  planDialogVisible.value = true
}

// 审批计划
const handleApprove = (row: Plan) => {
  console.log('审批计划:', row)
  loadPlanList()
}

// 删除计划
const handleDelete = (row: Plan) => {
  console.log('删除计划:', row)
  loadPlanList()
}

// 重置表单
const resetPlanForm = () => {
  planForm.id = 0
  planForm.name = ''
  planForm.dateRange = []
  planForm.remark = ''
  planForm.items = []
  addPlanItem()
}

// 添加计划项
const addPlanItem = () => {
  planForm.items.push({
    id: 0,
    category: 'electronics',
    productName: '',
    specification: '',
    quantity: 1,
    estimatedUnitPrice: 0
  })
}

// 删除计划项
const removePlanItem = (index: number) => {
  planForm.items.splice(index, 1)
}

// 确认计划操作
const confirmPlan = () => {
  console.log('确认计划操作:', planForm)
  planDialogVisible.value = false
  loadPlanList()
}

// 分页操作
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadPlanList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadPlanList()
}

// 生命周期
onMounted(() => {
  loadPlanList()
})
</script>

<style scoped>
.procurement-plans {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.list-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>